function [resid, coeff, info] = xt_demean(y,x,gr,gr_val)
% group demean
% y : variable to be meaned
% x : projector (vector of ones would produce demean)
% gr     : group of y (same length as y)
% gr_val : group values


[nobs, ny] = size(y);

info = [];
ngr = length(gr_val);

% gr_n = zeros(ngr,ny);
% n = [];

resid = [];
coeff = [];
for j=1:1:ny
    temp_resid = [];
    temp_coeff = [];
    for i = 1:1:ngr
        
        temp_y = y(gr==gr_val(i),j);
        temp_x = x(gr==gr_val(i),:);
        temp_n = size(temp_y,1);
        
        % group level projection
        temp_b = ( (temp_x'*temp_x)\(temp_x'*temp_y) );
        temp_e = temp_y-temp_x*temp_b; %residual from this projection
        temp_resid = [temp_resid; temp_e];
        temp_coeff = [temp_coeff; repmat(temp_b',temp_n,1)];
        
        %     %number of obs
        %     n = [n; repmat(temp_n,temp_n,1)]; %obs order
        %     gr_n(i,:) = temp_n; %gr order
        %
    end
    resid = [resid, temp_resid];
    coeff = [coeff, temp_coeff];
end
% info.n = n;
% info.gr_n = gr_n;
